<!DOCTYPE html>
<html lang="zh-cmn-Hans">
  <head>
    <meta charset="utf-8" />
    <title>单点登录</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <link rel="icon" href="../favicon.ico" />
    <script src="../static/config.js?t=001"></script>
    <script src="../js/js.cookie.min.js"></script>
    <script src="../js/common.js"></script>
    <script>
      let idaasParamNameTicketFlag = '';
      const redirectUrl = 'redirect_url';
      function oauth2Login() {
        // 清除token
        setSSOType('oauth2Login', Cookies);

        const { idaasServerLoginUrl, idaasParamNameService, idaasParamNameTicket } = window.$config.oauth2Option;
        idaasParamNameTicketFlag = idaasParamNameTicket;
        if (getParameterFromURL(idaasParamNameTicket)) {
          let service = window.location.href;
          service = service.substring(0, service.indexOf(`${idaasParamNameTicket}=`));
          service = service.endsWith('&') ? service.substring(0, service.length - 1) : service;
          service = service.endsWith('?') ? service.substring(0, service.length - 1) : service;
          const param = {
            ticket: getParameterFromURL(idaasParamNameTicket),
            service: service
          };
          const paramNames = {
            ticket: idaasParamNameTicket,
            service: idaasParamNameService
          };
          oauth2Auth(param, paramNames);
        } else {
          // 校验
          if (!idaasParamNameService) {
            throw new Error(`无法完成Oauth2认证: 缺失回调地址参数配置${idaasParamNameService}`);
          }
          // 2.根据参数配置跳转
          // 不进行编码，复杂的地址会被idds服务截断
          const href = encodeURIComponent(window.location.href);
          let url = idaasServerLoginUrl;
          if (url.indexOf('?') > -1) {
            url = `${url}&${idaasParamNameService}=${href}`;
          } else {
            url = `${url}?${idaasParamNameService}=${href}`;
          }
          window.location = url;
        }
      }
      function oauth2Auth(params, paramNames) {
        try {
          // 给接口传的地址与adds服务的地址保持一致
          const href = encodeURIComponent(params.service);
          const param = `?${paramNames.ticket}=${params.ticket}&${paramNames.service}=${href}`;
          fetch(`/api/appsys/sso/oauth2/login/v1${param}`, {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json'
            }
          })
            .then((response) => {
              // 多租户返回302时自动重定向，无需处理
              // if (!response.ok) {
              //   throw new Error('Network response was not ok ' + response.statusText);
              // }
              if (response.status === 200) {
                return response.json(); // 解析JSON数据
              }
            })
            .then((data) => {
              const { retCode, responseBody: result } = data;
              if (retCode === '200') {
                // 重定向优先级 redirectUrl > 后台用户
                if (window.location.href.indexOf(redirectUrl) > -1) {
                  storeData(result, Cookies);
                  let newPath = '';
                  const urlArr = decodeURIComponent(window.location.href.split(`${redirectUrl}=`)[1]);
                  if (urlArr.indexOf(idaasParamNameTicketFlag) > -1) {
                    const arr = urlArr.split('&');
                    const obj = {};
                    for (let i = 0; i < arr.length; i++) {
                      arr[i] = arr[i].split('=');
                      obj[arr[i][0]] = arr[i][1];
                    }
                    delete obj[idaasParamNameTicketFlag];
                    Object.keys(obj).forEach((key) => {
                      if (obj[key]) {
                        newPath += `${key}=${obj[key]}&`;
                      } else {
                        newPath += `${key}&`;
                      }
                    });
                    newPath = newPath.substring(0, newPath.length - 1);
                  } else {
                    newPath = urlArr;
                  }
                  const url = window.location.href.substring(0, window.location.href.indexOf('/oauth2login'));
                  window.name = 'portal';
                  window.location = `${url}${newPath}`;
                } else {
                  const { consoleUrl } = window.$config.consolePath;
                  if (result.userInfo && result.userInfo.consoleType === '0' && consoleUrl) {
                    consoleUrl = consoleUrl.endsWith('/') ? consoleUrl : `${consoleUrl}/`;
                    window.name = 'console';
                    window.open(`${consoleUrl}access-from-portal?access_token=${result.token}&redirect_url=/backstage`, 'console');
                  } else {
                    storeData(result, Cookies);
                    const url = window.location.href.substring(0, window.location.href.indexOf('/oauth2login'));
                    window.name = 'portal';
                    window.location = url + '/dashboard';
                  }
                }
              }
            });
        } catch (error) {
          console.error(error);
        }
      }
      oauth2Login();
    </script>
  </head>

  <body id="bodyThem">
    <div id="app"></div>
  </body>
</html>
